// 实时监控大屏功能模块
const React = window.React;
const ReactDOM = window.ReactDOM;
const { message, notification, Statistic, Progress } = window.antd;

// 实时监控大屏管理类
export default class MonitorDashboard {
    constructor() {
        this.refreshInterval = 30000; // 数据刷新间隔（毫秒）
        this.warningThresholds = {
            orderDecline: 20, // 订单量下降阈值（百分比）
            revenueDecline: 15, // 营收下降阈值（百分比）
            customerDecline: 25 // 客流量下降阈值（百分比）
        };
        this.currentData = null;
        this.previousData = null;
    }

    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initDashboard());
        } else {
            this.initDashboard();
        }
    }

    initDashboard() {
        // 确保主容器存在
        this.ensureMainContainer();
        
        // 初始化DOM元素
        this.contentWrapper = document.querySelector('.content-wrapper');
        if (!this.contentWrapper) {
            this.contentWrapper = document.createElement('div');
            this.contentWrapper.className = 'content-wrapper';
            document.querySelector('.main-container').appendChild(this.contentWrapper);
        }

        // 创建监控大屏界面
        this.contentWrapper.innerHTML = `
            <div class="monitor-dashboard-container">
                <div class="dashboard-header">
                    <h1>实时运营监控</h1>
                    <div class="refresh-info">数据更新时间：<span class="update-time"></span></div>
                </div>
                <div class="dashboard-grid">
                    <div class="dashboard-card" id="orderStats">
                        <h3>订单统计</h3>
                        <div class="stat-content">
                            <div class="main-stat"></div>
                            <div class="sub-stats">
                                <div class="stat-item" data-type="pending"></div>
                                <div class="stat-item" data-type="processing"></div>
                                <div class="stat-item" data-type="completed"></div>
                            </div>
                        </div>
                    </div>
                    <div class="dashboard-card" id="revenueStats">
                        <h3>营收统计</h3>
                        <div class="stat-content">
                            <div class="main-stat"></div>
                            <div class="trend-chart"></div>
                        </div>
                    </div>
                    <div class="dashboard-card" id="customerStats">
                        <h3>客流分析</h3>
                        <div class="stat-content">
                            <div class="main-stat"></div>
                            <div class="customer-distribution"></div>
                        </div>
                    </div>
                    <div class="dashboard-card" id="alertPanel">
                        <h3>异常预警</h3>
                        <div class="alert-list"></div>
                    </div>
                </div>
            </div>
        `;

        // 使用requestAnimationFrame确保DOM完全加载和样式应用后再初始化
        requestAnimationFrame(() => {
            this.initEventListeners();
            this.startDataRefresh();
            this.applyInitialStyles();
        });
    }

    // 确保主容器存在
    ensureMainContainer() {
        const mainContainer = document.querySelector('.main-container');
        if (!mainContainer) {
            const main = document.createElement('div');
            main.className = 'main-container';
            document.body.appendChild(main);
        }
    }

    // 应用初始样式
    applyInitialStyles() {
        const cards = document.querySelectorAll('.dashboard-card');
        cards.forEach(card => {
            card.style.opacity = '0';
            requestAnimationFrame(() => {
                card.style.transition = 'opacity 0.3s ease-in-out';
                card.style.opacity = '1';
            });
        });
    }

    // 初始化事件监听
    initEventListeners() {
        window.addEventListener('resize', this.handleResize.bind(this));
        
        // 添加卡片点击事件以显示详细信息
        document.querySelectorAll('.dashboard-card').forEach(card => {
            card.addEventListener('click', (e) => {
                const cardId = card.id;
                this.showDetailModal(cardId);
            });
        });
    }

    // 处理窗口大小变化
    handleResize() {
        // 实现响应式布局调整
        const container = document.querySelector('.monitor-dashboard-container');
        if (container) {
            const width = window.innerWidth;
            if (width < 1200) {
                container.classList.add('compact-view');
            } else {
                container.classList.remove('compact-view');
            }
        }
    }

    // 开始数据刷新循环
    startDataRefresh() {
        this.fetchAndUpdateData();
        setInterval(() => {
            this.fetchAndUpdateData();
        }, this.refreshInterval);
    }

    // 获取并更新数据
    async fetchAndUpdateData() {
        try {
            // 在实际应用中，这里会调用后端API获取实时数据
            const newData = await this.fetchMockData();
            this.previousData = this.currentData;
            this.currentData = newData;

            this.updateDashboard();
            this.checkAlerts();
            this.updateLastRefreshTime();
        } catch (error) {
            console.error('数据更新失败:', error);
            message.error('数据更新失败，请检查网络连接');
        }
    }

    // 更新仪表盘显示
    updateDashboard() {
        if (!this.currentData) return;

        // 更新订单统计
        this.updateOrderStats();

        // 更新营收统计
        this.updateRevenueStats();

        // 更新客流分析
        this.updateCustomerStats();
    }

    // 更新订单统计
    updateOrderStats() {
        const orderStats = this.currentData.orderStats;
        const mainStat = document.querySelector('#orderStats .main-stat');
        if (mainStat) {
            ReactDOM.render(
                React.createElement(Statistic, {
                    title: '今日订单总量',
                    value: orderStats.total,
                    suffix: '单'
                }),
                mainStat
            );
        }

        // 更新子统计数据
        const subStats = {
            pending: { label: '待处理', value: orderStats.pending },
            processing: { label: '处理中', value: orderStats.processing },
            completed: { label: '已完成', value: orderStats.completed }
        };

        Object.entries(subStats).forEach(([type, data]) => {
            const element = document.querySelector(`#orderStats .stat-item[data-type="${type}"]`);
            if (element) {
                ReactDOM.render(
                    React.createElement(Statistic, {
                        title: data.label,
                        value: data.value,
                        suffix: '单'
                    }),
                    element
                );
            }
        });
    }

    // 更新营收统计
    updateRevenueStats() {
        const revenueStats = this.currentData.revenueStats;
        const mainStat = document.querySelector('#revenueStats .main-stat');
        if (mainStat) {
            ReactDOM.render(
                React.createElement(Statistic, {
                    title: '今日总营收',
                    value: revenueStats.total,
                    prefix: '¥',
                    precision: 2
                }),
                mainStat
            );
        }

        // 更新趋势图表
        this.updateRevenueChart(revenueStats.hourlyData);
    }

    // 更新营收趋势图表
    updateRevenueChart(hourlyData) {
        const chartContainer = document.querySelector('#revenueStats .trend-chart');
        if (!chartContainer) return;

        // 确保echarts已加载
        if (!window.echarts) {
            console.error('ECharts is not loaded');
            return;
        }

        // 初始化或获取图表实例
        this.revenueChart = this.revenueChart || window.echarts.init(chartContainer);

        // 准备图表配置
        const option = {
            tooltip: {
                trigger: 'axis',
                formatter: '{b}时\n{c}元',
                backgroundColor: 'rgba(255,255,255,0.9)',
                borderColor: '#e6f7ff',
                textStyle: {
                    color: '#666'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: Array.from({length: 24}, (_, i) => i),
                axisLabel: {
                    formatter: '{value}时',
                    color: '#666'
                },
                axisLine: {
                    lineStyle: {
                        color: '#f0f0f0'
                    }
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}元',
                    color: '#666'
                },
                splitLine: {
                    lineStyle: {
                        color: '#f0f0f0',
                        type: 'dashed'
                    }
                }
            },
            series: [{
                data: hourlyData,
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 8,
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: 'rgba(24,144,255,0.3)'
                        }, {
                            offset: 1,
                            color: 'rgba(24,144,255,0.1)'
                        }]
                    }
                },
                itemStyle: {
                    color: '#1890ff',
                    borderWidth: 2,
                    borderColor: '#fff'
                }
            }]
        };

        // 设置图表配置
        this.revenueChart.setOption(option);

        // 监听窗口大小变化，调整图表大小
        window.addEventListener('resize', () => {
            this.revenueChart && this.revenueChart.resize();
        });
    }

    // 更新客流分析
    updateCustomerStats() {
        const customerStats = this.currentData.customerStats;
        const mainStat = document.querySelector('#customerStats .main-stat');
        if (mainStat) {
            ReactDOM.render(
                React.createElement(Statistic, {
                    title: '实时客流量',
                    value: customerStats.current,
                    suffix: '人'
                }),
                mainStat
            );
        }

        // 更新客流分布图表
        this.updateCustomerDistribution(customerStats.distribution);
    }

    // 更新客流分布图表
    updateCustomerDistribution(distribution) {
        const chartContainer = document.querySelector('#customerStats .customer-distribution');
        if (!chartContainer) return;

        // 确保echarts已加载
        if (!window.echarts) {
            console.error('ECharts is not loaded');
            return;
        }

        // 初始化或获取图表实例
        this.customerChart = this.customerChart || window.echarts.init(chartContainer);

        // 准备图表数据
        const data = [
            { value: distribution.new, name: '新客户' },
            { value: distribution.returning, name: '老客户' }
        ];

        // 准备图表配置
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 0
            },
            series: [{
                name: '客户类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }]
        };

        // 设置图表配置
        this.customerChart.setOption(option);

        // 监听窗口大小变化，调整图表大小
        window.addEventListener('resize', () => {
            this.customerChart && this.customerChart.resize();
        });
    }

    // 检查并显示警报
    checkAlerts() {
        if (!this.previousData || !this.currentData) return;

        const alerts = [];

        // 检查订单量变化
        const orderDecline = this.calculateDecline(
            this.previousData.orderStats.total,
            this.currentData.orderStats.total
        );
        if (orderDecline > this.warningThresholds.orderDecline) {
            alerts.push({
                type: 'warning',
                message: `订单量下降${orderDecline.toFixed(1)}%，超过警戒阈值`,
                timestamp: new Date()
            });
        }

        // 检查营收变化
        const revenueDecline = this.calculateDecline(
            this.previousData.revenueStats.total,
            this.currentData.revenueStats.total
        );
        if (revenueDecline > this.warningThresholds.revenueDecline) {
            alerts.push({
                type: 'warning',
                message: `营收下降${revenueDecline.toFixed(1)}%，超过警戒阈值`,
                timestamp: new Date()
            });
        }

        // 更新警报面板
        this.updateAlertPanel(alerts);
    }

    // 计算下降百分比
    calculateDecline(previous, current) {
        if (!previous || previous === 0) return 0;
        return ((previous - current) / previous) * 100;
    }

    // 更新警报面板
    updateAlertPanel(alerts) {
        const alertList = document.querySelector('#alertPanel .alert-list');
        if (alertList && alerts.length > 0) {
            alerts.forEach(alert => {
                notification[alert.type]({
                    message: '监控预警',
                    description: alert.message,
                    duration: 0
                });
            });

            // 更新警报列表
            const alertHtml = alerts.map(alert => `
                <div class="alert-item ${alert.type}">
                    <span class="alert-time">${alert.timestamp.toLocaleTimeString()}</span>
                    <span class="alert-message">${alert.message}</span>
                </div>
            `).join('');

            alertList.innerHTML = alertHtml + alertList.innerHTML;

            // 限制显示的警报数量
            const maxAlerts = 10;
            const alertItems = alertList.querySelectorAll('.alert-item');
            if (alertItems.length > maxAlerts) {
                for (let i = maxAlerts; i < alertItems.length; i++) {
                    alertItems[i].remove();
                }
            }
        }
    }

    // 更新最后刷新时间
    updateLastRefreshTime() {
        const timeElement = document.querySelector('.update-time');
        if (timeElement) {
            timeElement.textContent = new Date().toLocaleTimeString();
        }
    }

    // 显示详细信息模态框
    showDetailModal(cardId) {
        const cardData = this.currentData[cardId.replace('Stats', '')];
        if (!cardData) return;

        Modal.info({
            title: '详细数据',
            width: 600,
            content: this.renderDetailContent(cardId, cardData)
        });
    }

    // 渲染详细内容
    renderDetailContent(cardId, data) {
        // 根据不同卡片类型渲染不同的详细内容
        switch (cardId) {
            case 'orderStats':
                return this.renderOrderDetail(data);
            case 'revenueStats':
                return this.renderRevenueDetail(data);
            case 'customerStats':
                return this.renderCustomerDetail(data);
            default:
                return '暂无详细数据';
        }
    }

    // 模拟数据获取
    async fetchMockData() {
        return {
            orderStats: {
                total: Math.floor(Math.random() * 1000),
                pending: Math.floor(Math.random() * 100),
                processing: Math.floor(Math.random() * 200),
                completed: Math.floor(Math.random() * 700)
            },
            revenueStats: {
                total: Math.random() * 50000,
                hourlyData: Array.from({ length: 24 }, () => Math.random() * 2000)
            },
            customerStats: {
                current: Math.floor(Math.random() * 500),
                distribution: {
                    new: Math.floor(Math.random() * 100),
                    returning: Math.floor(Math.random() * 400)
                }
            }
        };
    }
}